// 进度管理系统 - 后台调用，为教学模块提供智能数据支持

export interface LearningProgress {
  currentLesson: number
  completedLessons: number[]
  learnedCharacters: CharacterProgress[]
  learnedRadicals: RadicalProgress[]
  learnedStrokes: StrokeProgress[]
  totalStudyTime: number
  lastStudyDate: string
}

export interface CharacterProgress {
  character: string
  lesson: number
  firstLearnedDate: string
  reviewCount: number
  masteryLevel: 'beginner' | 'intermediate' | 'advanced' | 'mastered'
  lastReviewDate: string
  correctRate: number
  usageInSentences: number
}

export interface RadicalProgress {
  radical: string
  lesson: number
  firstLearnedDate: string
  reviewCount: number
  relatedCharacters: string[]
  masteryLevel: 'beginner' | 'intermediate' | 'advanced' | 'mastered'
  teachingFrequency: number // 老师讲解次数
}

export interface StrokeProgress {
  stroke: string
  lesson: number
  firstLearnedDate: string
  reviewCount: number
  relatedCharacters: string[]
  masteryLevel: 'beginner' | 'intermediate' | 'advanced' | 'mastered'
}

export interface ContentGenerationRule {
  knownContentRatio: number // 已学内容比例 (0.7 = 70%)
  newContentRatio: number   // 新内容比例 (0.3 = 30%)
  difficultyLevel: 'easy' | 'medium' | 'hard'
}

export interface TeacherReminder {
  type: 'character' | 'radical' | 'stroke'
  content: string
  lesson: number
  reviewCount: number
  masteryLevel: string
  suggestion: string
  priority: 'low' | 'medium' | 'high'
}

class ProgressManager {
  private static instance: ProgressManager
  private progress: LearningProgress

  private constructor() {
    // 初始化进度数据（实际应用中从数据库加载）
    this.progress = this.loadProgress()
  }

  public static getInstance(): ProgressManager {
    if (!ProgressManager.instance) {
      ProgressManager.instance = new ProgressManager()
    }
    return ProgressManager.instance
  }

  // 加载学习进度（模拟数据）
  private loadProgress(): LearningProgress {
    return {
      currentLesson: 3,
      completedLessons: [1, 2],
      learnedCharacters: [
        {
          character: '木',
          lesson: 1,
          firstLearnedDate: '2024-01-01',
          reviewCount: 15,
          masteryLevel: 'mastered',
          lastReviewDate: '2024-01-15',
          correctRate: 0.95,
          usageInSentences: 8
        },
        {
          character: '人',
          lesson: 1,
          firstLearnedDate: '2024-01-01',
          reviewCount: 12,
          masteryLevel: 'advanced',
          lastReviewDate: '2024-01-14',
          correctRate: 0.88,
          usageInSentences: 6
        },
        {
          character: '水',
          lesson: 2,
          firstLearnedDate: '2024-01-08',
          reviewCount: 8,
          masteryLevel: 'intermediate',
          lastReviewDate: '2024-01-16',
          correctRate: 0.75,
          usageInSentences: 4
        },
        {
          character: '火',
          lesson: 2,
          firstLearnedDate: '2024-01-08',
          reviewCount: 6,
          masteryLevel: 'beginner',
          lastReviewDate: '2024-01-15',
          correctRate: 0.65,
          usageInSentences: 2
        }
      ],
      learnedRadicals: [
        {
          radical: '木',
          lesson: 1,
          firstLearnedDate: '2024-01-01',
          reviewCount: 20,
          relatedCharacters: ['木', '林', '森', '树'],
          masteryLevel: 'mastered',
          teachingFrequency: 8
        },
        {
          radical: '氵',
          lesson: 2,
          firstLearnedDate: '2024-01-08',
          reviewCount: 10,
          relatedCharacters: ['水', '河', '海', '湖'],
          masteryLevel: 'intermediate',
          teachingFrequency: 5
        },
        {
          radical: '亻',
          lesson: 1,
          firstLearnedDate: '2024-01-01',
          reviewCount: 15,
          relatedCharacters: ['人', '他', '们', '你'],
          masteryLevel: 'advanced',
          teachingFrequency: 6
        }
      ],
      learnedStrokes: [
        {
          stroke: '一',
          lesson: 1,
          firstLearnedDate: '2024-01-01',
          reviewCount: 25,
          relatedCharacters: ['一', '二', '三', '木'],
          masteryLevel: 'mastered'
        },
        {
          stroke: '丨',
          lesson: 1,
          firstLearnedDate: '2024-01-01',
          reviewCount: 20,
          relatedCharacters: ['丨', '中', '木', '水'],
          masteryLevel: 'advanced'
        }
      ],
      totalStudyTime: 1200, // 分钟
      lastStudyDate: '2024-01-16'
    }
  }

  // 获取当前进度
  public getProgress(): LearningProgress {
    return this.progress
  }

  // 获取已学汉字列表
  public getLearnedCharacters(): string[] {
    return this.progress.learnedCharacters.map(char => char.character)
  }

  // 获取已学部首列表
  public getLearnedRadicals(): string[] {
    return this.progress.learnedRadicals.map(radical => radical.radical)
  }

  // 检查汉字是否已学过
  public isCharacterLearned(character: string): boolean {
    return this.progress.learnedCharacters.some(char => char.character === character)
  }

  // 检查部首是否已学过
  public isRadicalLearned(radical: string): boolean {
    return this.progress.learnedRadicals.some(rad => rad.radical === radical)
  }

  // 获取汉字学习详情
  public getCharacterProgress(character: string): CharacterProgress | null {
    return this.progress.learnedCharacters.find(char => char.character === character) || null
  }

  // 获取部首学习详情
  public getRadicalProgress(radical: string): RadicalProgress | null {
    return this.progress.learnedRadicals.find(rad => rad.radical === radical) || null
  }

  // 为老师生成提醒信息
  public generateTeacherReminders(content: string[], type: 'character' | 'radical' | 'stroke'): TeacherReminder[] {
    const reminders: TeacherReminder[] = []

    content.forEach(item => {
      if (type === 'character') {
        const charProgress = this.getCharacterProgress(item)
        if (charProgress) {
          reminders.push({
            type: 'character',
            content: item,
            lesson: charProgress.lesson,
            reviewCount: charProgress.reviewCount,
            masteryLevel: charProgress.masteryLevel,
            suggestion: this.generateSuggestion(charProgress.masteryLevel, charProgress.reviewCount),
            priority: this.calculatePriority(charProgress.masteryLevel, charProgress.reviewCount)
          })
        }
      } else if (type === 'radical') {
        const radicalProgress = this.getRadicalProgress(item)
        if (radicalProgress) {
          reminders.push({
            type: 'radical',
            content: item,
            lesson: radicalProgress.lesson,
            reviewCount: radicalProgress.reviewCount,
            masteryLevel: radicalProgress.masteryLevel,
            suggestion: this.generateRadicalSuggestion(radicalProgress),
            priority: this.calculatePriority(radicalProgress.masteryLevel, radicalProgress.reviewCount)
          })
        }
      }
    })

    return reminders.sort((a, b) => {
      const priorityOrder = { high: 3, medium: 2, low: 1 }
      return priorityOrder[b.priority] - priorityOrder[a.priority]
    })
  }

  // 生成建议
  private generateSuggestion(masteryLevel: string, reviewCount: number): string {
    switch (masteryLevel) {
      case 'beginner':
        return `需要加强练习，建议多复习基础用法`
      case 'intermediate':
        return `掌握良好，可以尝试更多应用场景`
      case 'advanced':
        return `掌握较好，可以用于组词造句练习`
      case 'mastered':
        return `已熟练掌握，可以作为基础知识使用`
      default:
        return `继续保持练习`
    }
  }

  // 生成部首建议
  private generateRadicalSuggestion(radicalProgress: RadicalProgress): string {
    const { masteryLevel, teachingFrequency, relatedCharacters } = radicalProgress
    
    if (masteryLevel === 'mastered' && teachingFrequency >= 5) {
      return `已熟练掌握，可以用于讲解相关汉字：${relatedCharacters.slice(0, 3).join('、')}`
    } else if (masteryLevel === 'intermediate') {
      return `理解中等，建议结合具体汉字加强练习`
    } else {
      return `需要重点讲解，建议多举例说明`
    }
  }

  // 计算优先级
  private calculatePriority(masteryLevel: string, reviewCount: number): 'low' | 'medium' | 'high' {
    if (masteryLevel === 'beginner' || reviewCount < 5) {
      return 'high'
    } else if (masteryLevel === 'intermediate' || reviewCount < 10) {
      return 'medium'
    } else {
      return 'low'
    }
  }

  // 智能内容生成 - 按照已学/新学比例生成内容
  public generateSmartContent(
    allContent: string[],
    targetCount: number,
    rule: ContentGenerationRule = { knownContentRatio: 0.7, newContentRatio: 0.3, difficultyLevel: 'medium' }
  ): { knownContent: string[], newContent: string[], contentMix: string[] } {
    
    const learnedChars = this.getLearnedCharacters()
    
    // 分离已学和未学内容
    const knownContent = allContent.filter(item => learnedChars.includes(item))
    const newContent = allContent.filter(item => !learnedChars.includes(item))
    
    // 计算需要的数量
    const knownCount = Math.floor(targetCount * rule.knownContentRatio)
    const newCount = Math.floor(targetCount * rule.newContentRatio)
    
    // 随机选择内容
    const selectedKnown = this.shuffleArray(knownContent).slice(0, knownCount)
    const selectedNew = this.shuffleArray(newContent).slice(0, newCount)
    
    // 混合内容
    const contentMix = this.shuffleArray([...selectedKnown, ...selectedNew])
    
    return {
      knownContent: selectedKnown,
      newContent: selectedNew,
      contentMix
    }
  }

  // 为造句生成智能词汇
  public generateSentenceVocabulary(targetChar: string, sentenceCount: number = 3): string[][] {
    const sentences: string[][] = []
    const learnedChars = this.getLearnedCharacters()
    
    // 基础词汇库（应该从数据库获取）
    const vocabularyPool = {
      '木': ['树木', '木头', '森林', '大树', '小树'],
      '人': ['人类', '大人', '小人', '好人', '人们'],
      '水': ['水流', '喝水', '河水', '清水', '水果'],
      '火': ['火焰', '生火', '火车', '火山', '烟火']
    }
    
    const targetVocab = vocabularyPool[targetChar as keyof typeof vocabularyPool] || []
    
    for (let i = 0; i < sentenceCount; i++) {
      const sentence: string[] = []
      
      // 70%使用已学汉字，30%使用新汉字
      const knownWords = targetVocab.filter(word => 
        word.split('').every(char => learnedChars.includes(char))
      )
      const newWords = targetVocab.filter(word => 
        !word.split('').every(char => learnedChars.includes(char))
      )
      
      // 构建句子
      if (knownWords.length > 0) {
        sentence.push(knownWords[Math.floor(Math.random() * knownWords.length)])
      }
      if (newWords.length > 0 && Math.random() < 0.3) {
        sentence.push(newWords[Math.floor(Math.random() * newWords.length)])
      }
      
      sentences.push(sentence)
    }
    
    return sentences
  }

  // 更新学习进度
  public updateCharacterProgress(character: string, isCorrect: boolean): void {
    const charProgress = this.progress.learnedCharacters.find(char => char.character === character)
    if (charProgress) {
      charProgress.reviewCount++
      charProgress.lastReviewDate = new Date().toISOString().split('T')[0]
      
      // 更新正确率
      const totalAttempts = charProgress.reviewCount
      const correctAttempts = Math.floor(charProgress.correctRate * (totalAttempts - 1)) + (isCorrect ? 1 : 0)
      charProgress.correctRate = correctAttempts / totalAttempts
      
      // 更新掌握程度
      this.updateMasteryLevel(charProgress)
    }
  }

  // 更新掌握程度
  private updateMasteryLevel(progress: CharacterProgress): void {
    const { correctRate, reviewCount } = progress
    
    if (correctRate >= 0.9 && reviewCount >= 15) {
      progress.masteryLevel = 'mastered'
    } else if (correctRate >= 0.8 && reviewCount >= 10) {
      progress.masteryLevel = 'advanced'
    } else if (correctRate >= 0.7 && reviewCount >= 5) {
      progress.masteryLevel = 'intermediate'
    } else {
      progress.masteryLevel = 'beginner'
    }
  }

  // 工具函数：打乱数组
  private shuffleArray<T>(array: T[]): T[] {
    const shuffled = [...array]
    for (let i = shuffled.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
    }
    return shuffled
  }

  // 获取学习统计
  public getLearningStats(): {
    totalCharacters: number
    masteredCharacters: number
    totalRadicals: number
    masteredRadicals: number
    averageCorrectRate: number
    studyStreak: number
  } {
    const totalCharacters = this.progress.learnedCharacters.length
    const masteredCharacters = this.progress.learnedCharacters.filter(char => char.masteryLevel === 'mastered').length
    const totalRadicals = this.progress.learnedRadicals.length
    const masteredRadicals = this.progress.learnedRadicals.filter(rad => rad.masteryLevel === 'mastered').length
    
    const averageCorrectRate = this.progress.learnedCharacters.reduce((sum, char) => sum + char.correctRate, 0) / totalCharacters
    
    return {
      totalCharacters,
      masteredCharacters,
      totalRadicals,
      masteredRadicals,
      averageCorrectRate,
      studyStreak: 7 // 模拟连续学习天数
    }
  }

  // 保存进度（实际应用中保存到数据库）
  public saveProgress(): void {
    // 这里应该调用API保存到数据库
    console.log('进度已保存', this.progress)
  }
}

// 导出单例实例
export const progressManager = ProgressManager.getInstance()

// 导出工具函数
export const useProgressManager = () => {
  return {
    getProgress: () => progressManager.getProgress(),
    getLearnedCharacters: () => progressManager.getLearnedCharacters(),
    getLearnedRadicals: () => progressManager.getLearnedRadicals(),
    isCharacterLearned: (char: string) => progressManager.isCharacterLearned(char),
    isRadicalLearned: (radical: string) => progressManager.isRadicalLearned(radical),
    getCharacterProgress: (char: string) => progressManager.getCharacterProgress(char),
    getRadicalProgress: (radical: string) => progressManager.getRadicalProgress(radical),
    generateTeacherReminders: (content: string[], type: 'character' | 'radical' | 'stroke') => 
      progressManager.generateTeacherReminders(content, type),
    generateSmartContent: (allContent: string[], targetCount: number, rule?: ContentGenerationRule) =>
      progressManager.generateSmartContent(allContent, targetCount, rule),
    generateSentenceVocabulary: (targetChar: string, sentenceCount?: number) =>
      progressManager.generateSentenceVocabulary(targetChar, sentenceCount),
    updateCharacterProgress: (char: string, isCorrect: boolean) =>
      progressManager.updateCharacterProgress(char, isCorrect),
    getLearningStats: () => progressManager.getLearningStats(),
    saveProgress: () => progressManager.saveProgress()
  }
} 